package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.config.minio.config.MinioConfiguration;
import com.atguigu.gmall.common.config.minio.properties.MinioProperties;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.product.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @ClassName: FileServiceImpl
 * @Author: WDD
 * @CreateTime: 2022-12-02  01:06
 * @Description:
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    MinioProperties minioProperties;

    @Autowired
    MinioClient minioClient;

    @Override
    public String upload(MultipartFile file) throws Exception {
        //上传文件
        String date = DateUtil.formatDate(new Date());
        String filename = date + "/" + UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        PutObjectOptions options = new PutObjectOptions(file.getSize(), -1L);
        options.setContentType(file.getContentType());
        //上传
        minioClient.putObject(minioProperties.getBucketName(), filename, inputStream, options);
        //返回文件地址
        String url = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + filename;

        return url;
    }
}
